<template>
  <div class="detailList">
    <!-- 导航栏 -->
    <div class="fixedtab">

      <div class="navbar">
        <div class="left" @click="onClickLeft()">
          <img src="./../../assets/left.png" alt>
        </div>
        <div class="title">
          <span>{{this.$route.params.title}}</span>
        </div>
        <div class="right" @click="onClickRight()">
          <img src="./../../assets/icon_refurbish@3x.png" alt />
        </div>
      </div>

      <!-- tab选项卡 -->
      <div v-if="ishomeselect" class="tab">
        <div @click="tabClick(1)">
          <span :class="{act:selectType==0}">{{selectMainName}}</span>
          <img :src="tabApp" alt />
        </div>
        <div @click="tabClick(2)">
          <span :class="{act:selectType==1}">{{selectSecondName}}</span>
          <img :src="tabType" alt />
        </div>
      </div>
      <div v-else class="tab">
        <div>
          <span>全部</span>
        </div>
        <div>
          <span>按天</span>
        </div>
      </div>
    </div>

    <!-- tab蒙版，item -->
    <div class="itembox" v-show="showtab">
      <div class="bg" @click="backfalse()"></div>
      <div class="content" v-if="selectArr&&selectArr.length!=0">
        <div
          v-for="(item,index) in selectArr"
          @click="selectItem(item)"
          :class="['item',{itemact:item.act==true}]"
          :key="index"
        >{{item.label}}</div>
      </div>
    </div>
    <!-- 折线图 -->
    <!-- <van-pull-refresh v-model="isLoading" @refresh="onRefresh"> -->
    <div class="map" v-show="isShowLine==1" id="map"></div>
    <div class="map" v-show="isShowLine!=1" id="map2"></div>
    <!-- 数据列表 -->
    <!-- <tableList :tableList="tableListData" :titlename="titlename" :tips="tips"></tableList> -->
    <div>
      <div
        v-if="tableListData&&tableListData.length!=0&&Object.keys(tableListData[0]).length==3"
        class="infobox"
      >
        <div class="title group">
          <div>{{titlename}}</div>
          <div>数据</div>
          <div>环比</div>
        </div>
        <div class="groupbox" v-if="tableListData.length!=0">
          <div v-for="(item,index) in tableListData" :key="index" class="group">
            <div>{{item.time}}</div>
            <div>{{item.data}}</div>
            <div v-if="item.ratio.indexOf('-')>-1" class="green">
              <span>-</span>
              <span>{{item.ratio.split('-')[1]}}</span>
            </div>
            <div v-else class="red">
              <span>+</span>
              <span>{{item.ratio}}</span>
            </div>
          </div>
          <div class="help" v-if="!!tips">
            <div style="margin-top:10px;margin-bottom:5px;">备注：</div>
            <div v-html="tips"></div>
          </div>
        </div>
      </div>
      <div
        v-else-if="tableListData&&tableListData.length!=0&Object.keys(tableListData[0]).length==4"
        class="infobox"
      >
        <div class="title group">
          <div>{{titlename}}</div>
          <div @click="selectclick()">
            <span>{{currentDate2}}</span>
            <img src="./../../assets/icon_Triangle_down1@3x.png" />
          </div>
          <div>今日</div>
          <div>同比</div>
        </div>
        <div class="groupbox" v-if="tableListData.length!=0">
          <div v-for="(item,index) in tableListData" :key="index" class="group">
            <div>{{item.time}}</div>
            <div>{{item.yData}}</div>
            <div>{{item.data}}</div>
            <div v-if="item.ratio.indexOf('-')>-1" class="green">
              <span>-</span>
              <span>{{item.ratio.split('-')[1]}}</span>
            </div>
            <div v-else class="red">
              <span>+</span>
              <span>{{item.ratio}}</span>
            </div>
          </div>
          <div class="help" v-if="!!tips">
            <div>备注：</div>
            <div v-html="tips"></div>
          </div>
        </div>
      </div>
      <div v-else class="infobox">
        <div class="title group">
          <div>{{titlename}}</div>
          <div @click="selectclick()">
            <span>{{currentDate2}}</span>
            <img src="./../../assets/icon_Triangle_down1@3x.png" />
          </div>
          <div>今日</div>
          <div>同比</div>
        </div>
        <div class="groupbox">
          <div class="group">
            <div style="text-align:center;">暂无数据</div>
          </div>
          <div class="help" v-if="!!tips">
            <div style="margin-top:10px;margin-bottom:5px;">备注：</div>
            <div v-html="tips"></div>
          </div>
        </div>
      </div>
      <div class="datapic" v-show="dataselect">
        <div class="bg" @click="dataselect=false"></div>
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @cancel="dcancel()"
          @confirm="confirm"
          :min-date="minDate2"
          :max-date="minDate"
        />
      </div>
    </div>
  </div>
</template>

<script>
import down from "./../../assets/icon_Triangle_down1@3x.png";
import up from "./../../assets/icon_Triangle_up1@3x.png";
import echarts from 'echarts';
import option from './../common/option'
import { DatetimePicker,NavBar,Toast} from 'vant';
Vue.use(DatetimePicker,NavBar);
Vue.use(Toast);

import api from "./../common/api.js";
function yesterday() {
  var yesterday = new Date(new Date() - 1000 * 60 * 60 * 24);
  var y = yesterday.getFullYear();
  var m = yesterday.getMonth() + 1;
  var d = yesterday.getDate();
  return y + "-" + m + "-" + d;
}
var myechat=null;
var myechat2=null;
export default {
  data() {
    return {
      showtab: false, //显示选项卡
      tabApp: down, //展开图标
      tabType: down, //收起图标
      isLoading: false, //加载中
      isShowLine: 1, //展示单个曲线
      minDate: (function() {
        var yesterday = new Date(new Date() - 1000 * 60 * 60 * 24);
        var y = yesterday.getFullYear();
        var m = yesterday.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = yesterday.getDate();
        d = d < 10 ? "0" + d : d;
        return new Date(y + "-" + m + "-" + d);
      })(),
      minDate2: new Date("2019-01-01"),
      currentDate: (function() {
        var yesterday = new Date(new Date() - 1000 * 60 * 60 * 24);
        var y = yesterday.getFullYear();
        var m = yesterday.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = yesterday.getDate();
        d = d < 10 ? "0" + d : d;
        return new Date(y + "-" + m + "-" + d);
      })(), //当前选择日期1
      currentDate2: "昨日", //当前选择日期1
      dataselect: false, //日期选项控制
      selectMainArr: [
        // { label: "全部", id: 0, act: true },
        { label: "App", id: 1, act: true },
        { label: "iOS", id: 2, act: false },
        { label: "Android", id: 3, act: false },
        { label: "小程序", id: 4, act: false }
        // { label: "H5", id: 5, act: false }
      ], //选项数组--主选项
      selectSecondArr: [
        { label: "按时", id: 0, act: true },
        { label: "按天", id: 1, act: false },
        { label: "按周", id: 2, act: false },
        { label: "按月", id: 3, act: false }
      ], //选项数组-次选项
      selectMainName: "App", //主选项名称
      selectSecondName: "按时", //主选项名称
      selectArr: [], //选项数组
      selectType: 2, //点击选项
      tableListData: [{}], //列表数据
      tabData: { appC: 1, timeC: 0 },
      tempdata: {},
      titlename: "按天",
      ishomeselect: false, //首页进来
      tips: "", //底部提示
      newxArr:[
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20",
        "21",
        "22",
        "23"
      ]
    };
  },
  mounted() {
    // 使用刚指定的配置项和数据显示图表。
    if (window.sessionStorage.getItem("fromhome2") == 1) {
      this.titlename = "按时";
    }
    this.initData(data => {
      this.dealData(data);
    });
  },
  methods: {
    initData(callback) {
      var firstData = Object.assign(this.$route.params.baseData, this.tabData);
      if (window.localStorage.getItem("selectItem2") == "首页") {
        this.ishomeselect = true;

        if (!!window.sessionStorage.getItem("seceondClick2")) {
          firstData = Object.assign(this.$route.params.baseData, this.tabData);
        } else {
          // this.titlename = "按时";
          firstData = Object.assign(this.$route.params.baseData, this.tabData);
        }
      } else {
        this.tabData.timeC = 1;
        this.tabData.appC = 0;
        firstData = Object.assign(this.$route.params.baseData, this.tabData);
      }
    
      this.$fetch.getDataNew(api.apiUrl, firstData, data => {
       
        if (data.result == 1) {
          if (data.data.length != 0) {
            var tempData = {};

            this.tableListData = JSON.stringify(data.data);
            this.tips = data.tips;
            if (Object.keys(data.data[0]).length == 3) {
              tempData.type = 1;
            } else {
              tempData.type = 2;
            }
            tempData.value = 1;
            tempData.data = data.data.sort(() => {
              return -1;
            });
            // this.tableListData=this.tableListData.sort(() => {
            //   return -1;
            // });
            this.tableListData = JSON.parse(this.tableListData);
            callback(tempData);
          } else {
            // alert('无此类型数据')

            var tempData = {};
            var tempData2 = [];
            this.tableListData = JSON.stringify([{ a: 1 }]);
            this.tips = data.tips;
            tempData.type = 2;
            tempData.value = 2;
            callback(tempData);
          }
        } else {
             Toast(data.message)
        }
      });
    },
    dealData(data) {
      if (data.type == 1) {
        var xArr = [],
          yArr = [];

        data.data.forEach((v, index) => {
          if (v.data.indexOf(",") > -1) {
            v.data = v.data.replace(/,/g, "");
          }

          xArr.push(v.time);
          v.data = parseFloat(v.data);
          yArr.push(parseFloat(v.data));
        });
        if (Math.max(...yArr) > 10000) {
          yArr = yArr.map(v => {
            return (v / 10000).toFixed(2);
          });

          option.option.option1.yAxis[0].name = "万";
        }

        option.option.option1.xAxis[0].data = xArr;
        option.option.option1.series[0].data = yArr;
        this.isShowLine = 1;

        option.option.option1.legend.data[0].name = this.$route.params.title;
        option.option.option1.series[0].name = this.$route.params.title;
        console.log(option.option.option1,9999888)
        // myechat = echarts.init(document.getElementById("map"),null,{renderer:'svg'});
        myechat = echarts.init(document.getElementById("map"));
        myechat.setOption(option.option.option1);
        this.$forceUpdate();
      } else {
        var xArr = [],
          tArr = [],
          yArr = [];
        var tempArr=[];

        if (data.value == 1) {
          for (var i = 0; i < 24; i++) {
            var obj={};
            obj.time=i<10?'0'+i+':00':i+':00';
            obj.ratio=0;
            obj.data=null;
            obj.yData=null;

            if (data.data.length!=0){
              for (let j = 0; j < data.data.length; j++) {
                var tempstr=data.data[j].time;
                tempstr=tempstr.split(':')[0];
                tempstr=parseInt(tempstr)<10?'0'+parseInt(tempstr)+':00':tempstr+':00';
                if (obj.time==tempstr){
                  obj.time=data.data[j].time;
                  obj.ratio=data.data[j].ratio;
                  obj.data=data.data[j].data;
                  obj.yData=data.data[j].yData;
                }
              }
            }
            tempArr.push(obj);

          }
          data.data=tempArr;
          data.data.forEach((v, index) => {
            // v.time=v.time.replace(/[^0-9]/ig,"");
            // v.time=v.time.toString().slice(5,v.time.length)
            //  v.time=(v.time/100).toFixed(2)
            xArr.push(v.time);
            //
            if (v.data&&v.data.indexOf(",") > -1) {
              v.data = v.data.replace(/,/g, "");
            }
            if (v.yData&&v.yData.indexOf(",") > -1) {
              v.yData = v.yData.replace(/,/g, "");
            }
            v.data = v.data?parseFloat(v.data):v.data;
            v.yData = v.yData?parseFloat(v.yData):v.yData;
            tArr.push(v.data);
            yArr.push(v.yData);
          });

          if (Math.max(...yArr) > 10000 || Math.max(...tArr) > 10000) {
            yArr = yArr.map(v => {
              return v?parseFloat((v / 10000).toFixed(6)):v;
            });
            tArr = tArr.map(v => {
              return v?parseFloat((v / 10000).toFixed(6)):v;
            });
            option.option.option2.yAxis[0].name = "万";
          }

          option.option.option2.xAxis[0].data = this.newxArr;
          option.option.option2.series[0].data = tArr;
          option.option.option2.series[1].data = yArr;
        } else {
          option.option.option2.xAxis[0].data = xArr;
          option.option.option2.series[0].data = tArr;
          option.option.option2.series[1].data = yArr;
        }

        this.isShowLine = 2;
        // myechat2 = echarts.init(document.getElementById("map2"),null,{renderer:'svg'});
        myechat2 = echarts.init(document.getElementById("map2"));
        myechat2.setOption(option.option.option2);
        this.$forceUpdate();
      }
    },
    onClickLeft() {
      this.$router.go(-1); //返回上一层
    },
    tabClick(type) {
      this.showtab = true;
      window.sessionStorage.setItem("seceondClick2", 1);
      if (type == 1) {
        if (this.tabApp == up) {
          this.showtab = false;
          this.tabApp = down;
          this.selectType = 2;
          return;
        }
        this.selectType = 0;
        this.tabApp = up;
        this.tabType = down;
        this.selectArr = this.selectMainArr;
      } else {
        if (this.tabType == up) {
          this.showtab = false;
          this.selectType = 2;
          this.tabType = down;
          return;
        }
        this.selectType = 1;
        this.tabApp = down;
        this.tabType = up;
        this.selectArr = this.selectSecondArr;
      }
    },
    selectItem(item) {
      this.showtab = false;
      this.tabApp = down;
      this.tabType = down;

      if (this.selectType == 0) {
        this.selectMainName = item.label;
        this.selectType = 2;
        this.selectMainArr.forEach((v, index) => {
          v.act = false;
        });
        this.tabData.appC = item.id;
        item.act = true;
      } else {
        this.selectType = 2;
        this.selectSecondName = item.label;
        this.titlename = item.label;
        this.selectSecondArr.forEach((v, index) => {
          v.act = false;
        });
        this.tabData.timeC = item.id;
        item.act = true;
      }
      this.initData(data => {
        this.dealData(data);
      });
    },
    backfalse() {
      this.showtab = false;
      this.tabApp = down;
      this.tabType = down;
      this.selectType = 2;
    },
    onRefresh() {
      setTimeout(() => {}, 500);
    },
    dcancel() {
      this.dataselect = false;
    },
    selectclick() {
      this.dataselect = true;
    },
    confirm(val) {
      var marr = document.getElementsByClassName(
        "van-picker-column__item--selected"
      );

      var text = "";
      for (let i = 0; i < marr.length; i++) {
        if (i == marr.length - 1) {
          text += parseInt(marr[i].innerText);
        } else {
          text += parseInt(marr[i].innerText) + "-";
        }
      }

      this.tabData.time = text;
      this.currentDate2 = text;
      option.option.option2.legend.data[1].name = text;
      option.option.option2.series[1].name = text;
      this.initData(data => {
        this.isLoading = false;
        document.getElementsByClassName("groupbox")[0].scrollTop = 0;
        this.dealData(data);
        if (text == yesterday()) {
          option.option.option2.legend.data[1].name = "昨日";
          option.option.option2.series[1].name = "昨日";
          this.currentDate2 = "昨日";
          this.myChart.setOption(option.option.option2);
          this.$forceUpdate();
        }
      });
      this.dataselect = false;
    },
    onClickRight() {
      this.initData(data => {
        this.isLoading = false;
        document.getElementsByClassName("groupbox")[0].scrollTop = 0;
        this.dealData(data);
      });
    }
  },
  destroyed() {
    if (myechat){
      myechat.clear();
    }
    if (myechat2){
      myechat2.clear();
    }

    // option.option.option1=null;
    // option.option.option2=null;
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/home") {
      to.meta.keepAlive = true;
    } else {
      to.meta.keepAlive = false;
    }
    next();
  }
};
</script>
<style lang="stylus" scoped>
.map {
  width: 96vw;
  margin: auto;
  height: 7rem;
  box-shadow: 0 3px 6px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.datapic {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.5);

  &>div {
    position: fixed;
    width: 100vw;
    height: 38vh;
    bottom: 0;
    z-index: 1002;
  }

  &>.bg {
    position: fixed;
    width: 100vw;
    height: 100vh;
    bottom: 0;
    z-index: 1001;
  }
}

@media screen and (max-width: 374px) and (min-width: 320px) and (-webkit-min-device-pixel-ratio: 2) {
  /* 兼容iphone4~5 */
}

@media screen and (max-width: 414px) and (min-width: 375px) and (-webkit-min-device-pixel-ratio: 2) {
  /* 兼容iphone5~6p */
}

@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  /* iphoneX、iphoneXs */
}

@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
  /* iphone Xs Max */
}

@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
  /* iphone XR */
}

@media only screen and (min-device-width: 1080px) and (-webkit-min-device-pixel-ratio: 2.5) {
  /* 魅族 */
}

@media only screen and (min-device-width: 1080px) and (-webkit-min-device-pixel-ratio: 3) {
  /* mate7 */
}

@media only screen and (min-device-width: 361px) and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 1) {
  /* 奇葩安卓机(一般为这个)dpr统一为1 Nexus  Galaxy 5s 5X,6p 魅族 */
}
</style>
